//后台配置/数据配置

import React, { Component } from 'react';
import { connect } from 'dva';
import { Tree, Card, Cascader, Button, Input, Icon, Divider, Table, InputNumber, Popconfirm, Form, Pagination, Checkbox, DatePicker } from 'antd';
import styles from './VideoHistory.less';


import request from '../../utils/request';
import PublicService from '../../services/PublicService';
import { Row, Col, Collapse, message } from 'antd';
import { DragDropContext } from 'react-dnd';
import HTML5Backend, { NativeTypes } from 'react-dnd-html5-backend';
import Dustbin from './component/Dustbin';
import moment from 'moment';
import Box from './component/Box';
import Filt from './component/Filt';
const lastDroppedItem111 = require("../../assets/rq2.mp4")
const fengm = require("../../assets/fengm1.png")
const Panel = Collapse.Panel;
const { TreeNode } = Tree;
class VideoHistory extends Component {
  state = {
    treeValue: "",
    treeData: [
      {
        children: [
          {
            children: [
              {
                children: [
                  {
                    pid: "#1燃气站",
                    title: "张三",
                    value: "张三"
                  },
                  {
                    pid: "#1燃气站",
                    title: "李四",
                    value: "李四"
                  }
                ],
                pid: "#1企业",
                title: "#1燃气站",
                value: "#1燃气站"
              },
              {
                children: [
                  {
                    pid: "#2燃气站",
                    title: "王五",
                    value: "王五"
                  },
                  {
                    pid: "#2燃气站",
                    title: "李四",
                    value: "李四"
                  }
                ],
                pid: "#1企业",
                title: "#2燃气站",
                value: "#2燃气站"
              }
            ],
            pid: "全部",
            title: "#1企业",
            value: "#1企业"
          },
          {
            children: [
              {
                children: [
                  {
                    pid: "#3燃气站",
                    title: "田七",
                    value: "田七"
                  },
                  {
                    pid: "#3燃气站",
                    title: "王九",
                    value: "王九"
                  }
                ],
                pid: "#2企业",
                title: "#3燃气站",
                value: "#3燃气站"
              }
            ],
            pid: "全部",
            title: "#2企业",
            value: "#2企业"
          }
        ],
        pid: "0",
        title: "全部",
        value: "全部"
      }
    ],
    width: '100%',
    num: 24,
    height: '85vh',
    video: '70vh',
    dustbins: [
      { accepts: ['true'], open: false, padding: '0 1vw 0 1vw', marginTop: '1.5vh', name: "视频1" },
    ],
    boxes: [
      {
        title: '项目部',
        sub: [
          { name: '点位1', type: 'true', url: 'rtmp://live.hkstv.hk.lxdns.com/live/hks' },
          { name: '点位2', type: 'true', url: 'rtmp://live.hkstv.hk.lxdns.com/live/hks' },
          { name: '点位3', type: 'true', url: 'rtmp://live.hkstv.hk.lxdns.com/live/hks' },
          { name: '点位4', type: 'true', url: 'rtmp://live.hkstv.hk.lxdns.com/live/hks' },
          { name: '点位5', type: 'true', url: 'rtmp://live.hkstv.hk.lxdns.com/live/hks' },
          { name: '点位6', type: 'true', url: 'rtmp://live.hkstv.hk.lxdns.com/live/hks' }
        ],
      },
      {
        title: '项目现场',
        sub: [
          { name: '点位1', type: 'true', url: 'rtmp://live.hkstv.hk.lxdns.com/live/hks' },
          { name: '点位2', type: 'true', url: 'rtmp://live.hkstv.hk.lxdns.com/live/hks' },
          { name: '点位3', type: 'true', url: 'rtmp://live.hkstv.hk.lxdns.com/live/hks' },
          { name: '点位4', type: 'true', url: 'rtmp://live.hkstv.hk.lxdns.com/live/hks' },
          { name: '点位5', type: 'true', url: 'rtmp://live.hkstv.hk.lxdns.com/live/hks' },
          { name: '点位6', type: 'true', url: 'rtmp://live.hkstv.hk.lxdns.com/live/hks' }
        ],
      }

    ],
    droppedBoxNames: [],
    loading: false,
    options: [],
    toggle: false,
    playUrl: '',
  };
  componentDidMount() {


    request({
      url: '/zhrq-web/gas/deliverystaff/getCamera',
      method: 'POST',
      data: {}
    }).then(data => {
      this.setState({
        treeData: data.ret.resultList
      })
    })





    let t = this;
    t.setState({
      loading: true,
    });
    let options = [];
    request({
      url: '/jnhj/company/getAllCompanyName',
      method: 'GET'
    }).then(data => {
      //   data.ret.map(item => {
      //     options.push({text:item.name,value:item.id})
      //   });
    })
    t.setState({
      options
    });
    t.onSearch();
  }

  isDropped(boxName) {
    return this.state.droppedBoxNames.indexOf(boxName) > -1;
  }
  //鼠标松开事件
  /**
   *  参数(@index 容器的下标  @item 拖动的name  @box 携带播放所需的信息)
   **/
  handleDrop(index, item, box) {
    let t = this;
    t.setState({
      toggle: true
    });
    /*
    * 此处t.setState执行两个参数，t.setState(update(this.state,{}),()=>{})
    * 第一个参数用于关闭播放器
    * 第二个参数用于开启播放器并更新播放的相关信息
    * update 扩展不变的数据（immutability-helper） 可参考github地址:https://github.com/kolodny/immutability-helper
    * {$set: any} 直接赋值覆盖
    * {$push: array} 数组中的push()语法
    * */
    t.setState(
      update(this.state, {
        dustbins: {
          [index]: {
            open: {
              $set: false,
            }
          },
        }
      }),
      () => {
        const { name } = item;
        let url = '';
        for (let i = 0; i < box.length; i++) {
          box[i].sub.map(item => {
            if (item.name === name) {
              url = item.url
            }
          })
        }
        const droppedBoxNames = name ? { $push: [name] } : {};
        this.setState(
          update(this.state, {
            dustbins: {
              [index]: {
                name: {
                  $set: name,
                },
              },
            },
            droppedBoxNames,
            playUrl: {
              $set: url
            },
          }),
        )
      }
    )
  }
  //查询
  onSearch() {
    let t = this;
    t.f1.getForm().validateFields((err, value) => {
      if (!err) {
        t.setState({
          loading: true,
        });
        request({
          method: 'GET',
          url: '/jnhj/visCamera/getVisListByBindObjId',
          params: {
            projectCompanyId: value.projectCompanyId,
          }
        }).then(data => {
          let boxes = [];
          data.ret.map((item, index) => {
            let title = item.name;
            let sub = [];
            item.cameraList.map((items, index) => {
              sub.push({ name: items.cameraName, type: 'true', url: items.cameraCode })
            });
            boxes.push({ title, sub })
          });
          t.setState({
            boxes,
            loading: false,
          })
        }).catch((err) => {
          message.error('查询出错')
        })
      }
    })
  }
  //播放
  onPlay() {
    let t = this;
    t.f1.getForm().validateFields((err, value) => {
      if (!err) {
        let playUrl = t.state.playUrl;
        let startTime = moment(moment(value.playTime[0]).format('YYYY-MM-DD HH:mm:ss')).diff(0);
        let endTime = moment(moment(value.playTime[1]).format('YYYY-MM-DD HH:mm:ss')).diff(0);
        request({
          method: 'GET',
          url: '/jnhj/visCamera/getHisVideoUrlByCode',
          params: {
            cameraCode: playUrl,
            startTime,
            endTime,
          }
        }).then(data => {
          // let url = data.ret;
          let url = data.ret;
          this.setState(
            update(this.state, {
              dustbins: {
                [0]: {
                  lastDroppedItem: {
                    $set: url,
                  },
                  open: {
                    $set: true,
                  }
                },
              },
            }),
          )
        })
      }
    })
  }

  //树形控件

  renderTreeNodes = data => data.map((item) => {
    if (item.children) {
      return (
        <TreeNode title={item.title} key={item.key} dataRef={item}>
          {this.renderTreeNodes(item.children)}
        </TreeNode>
      );
    }
    return <TreeNode {...item} />;
  })

  onDragEnter = (v, b, n) => {
    console.log(v, b, n)
    if (b.selectedNodes[0].props.value) {
      this.setState({
        treeValue: b.selectedNodes[0].props.pid + b.selectedNodes[0].props.value
      })
    }

  }

  onOPen = () => {
    // let url = data.ret;
    var options = {
      captionsButton: false,
      chaptersButton: false,
      liveDisplay: false,
      playbackRateMenuButton: false,
      subtitlesButton: false
    };

    var player = videojs('my-player', options, function onPlayerReady() {
      videojs.log('Your player is ready!');

      // In this context, `this` is the player that was created by Video.js.
      this.play();

      // How about an event listener?
      this.on('ended', function () {
        videojs.log('Awww...over so soon?!');
      });
    });



    // var player = videojs("example_video_1", {
    //   "techOrder": ["flash", "html"],
    //   "autoplay": false,
    //   control: {
    //     captionsButton: false,
    //     chaptersButton: false,
    //     liveDisplay: false,
    //     playbackRateMenuButton: false,
    //     subtitlesButton: false
    //   }

    // }, function () {

    //   this.on('loadeddata', function () {
    //     console.log(this)
    //   })

    //   this.on('ended', function () {
    //     this.pause();
    //     this.hide()
    //   })

    // });


  }

  pause = () => {
    var options = {
      captionsButton: false,
      chaptersButton: false,
      liveDisplay: false,
      playbackRateMenuButton: false,
      subtitlesButton: false
    };

    var player = videojs('my-player', options, function onPlayerReady() {
      videojs.log('Your player is ready!');

      // In this context, `this` is the player that was created by Video.js.
      this.pause()

      // How about an event listener?
      this.on('ended', function () {
        videojs.log('Awww...over so soon?!');
      });
    });
  }
  render() {
    let t = this;
    const { boxes, dustbins, options, treeData } = t.state;
    const items = [
      {
        type: 'rangePicker',
        label: '播放时间',
        paramName: 'playTime',
        showTime: [{
          hideDisabledOptions: true,
          defaultValue: [moment('00:00:00', 'HH:mm:ss'), moment('11:59:59', 'HH:mm:ss')],
        }],
        format: 'YYYY-MM-DD HH:mm:ss',
        toggle: t.state.toggle
      },
      {
        type: 'select',
        label: '时间选取',
        paramName: 'projectCompanyId',
        options: options
      }, {
        type: 'query'
      }, {
        type: 'rangePicker',
        label: '播放时间',
        paramName: 'playTime',
        showTime: [{
          hideDisabledOptions: true,
          defaultValue: [moment('00:00:00', 'HH:mm:ss'), moment('11:59:59', 'HH:mm:ss')],
        }],
        format: 'YYYY-MM-DD HH:mm:ss',
        toggle: t.state.toggle
      }, {
        type: 'play',
        toggle: t.state.toggle
      }
    ]

    return (
      <div>
        {/* <Filt key="Filt" items={items} ref={ref=>t.f1=ref} submit={t.onSearch.bind(t)} play={t.onPlay.bind(t)} clearBtn={'hide'}/> */}
        <Row gutter={12} style={{ clear: 'both'}}>
          <Col xs={18} sm={18} md={18} lg={18} xl={18} style={{margin:"2vh 0px 1vh 0px"}}>
            <div className={styles['wp-video']} style={{ clear: 'both'}}>
              <Row style={{ marginTop: '1vh' }}>
                <Col span={6}>
                  <div className={styles.blueBlock}><i></i><span>视频管理 >> 历史视频</span></div>
                </Col>
              </Row>
              <Row>
                {/* {
                  dustbins.map(({ accepts, lastDroppedItem, name, padding, marginTop, open }, index) => (
                    <Col key={index} md={t.state.num} lg={t.state.num} xl={t.state.num}>
                      <Dustbin
                        key={index}
                        load={t.state.load}
                        name={name}
                        open={open}
                        padding={padding}
                        marginTop={marginTop}
                        accepts={accepts}
                        lastDroppedItem={lastDroppedItem111}
                        width={t.state.width}
                        height={t.state.height}
                        video={t.state.video}
                        onDrop={item => this.handleDrop(index, item, t.state.boxes)}
                      />
                     
                    </Col>
                  ))
                } */}




              </Row>
              <div style={{width:"100%",height:"96.4%",padding:"0.7vw 1vw 0.5vw 1vw"}}>
                <video
                id="my-player"
                style={{ width: "100%", height: "100%", objectFit: "fill" }}
                poster={fengm}
                data-setup='{}'>
                <source src={lastDroppedItem111} type="video/mp4"></source>
              </video>
              </div>

            </div>
          </Col>
          <Col xs={6} sm={6} md={6} lg={6} xl={6} style={{margin:"2vh 0px 1vh 0px"}}>
            <div className={styles['wp-video']}>
              <div className={styles.blueBlock} style={{ paddingTop: '10px' }}><i style={{ height: 14, width: 5, backgroundColor: "#3C8FFF", marginRight: 20 }}></i><span style={{ textAlign: "left", fontWeight: 'normal', margin: "0 10px", borderBottom: "1px solid #ccc", paddingBottom: 10 }}> 时间选取</span></div>
              <Row>
                <div style={{ height: '79vh', overflow: 'auto', marginTop: '10px' }}>
                  {/* <Collapse bordered={false} accordion >
                          <Panel header="项目部" key="1" style={{border: 0,color:'#1A1A1A',fontSize:'14px',fontWeight:'bold',}}>
                            {
                              boxes[0].sub.map(({ name, type, url }, index) => (
                                <Box
                                  key={index}
                                  name={name}
                                  type={type}
                                  isDropped={this.isDropped(type)}
                                />
                              ))
                            }
                          </Panel>
                          <Panel header="项目现场" key="2" style={{border: 0,color:'#1A1A1A',fontSize:'14px',fontWeight:'bold',}}>
                            {
                              boxes[1].sub.map(({ name, type, url }, index) => (
                                <Box
                                  key={index}
                                  name={name}
                                  type={type}
                                  isDropped={this.isDropped(type)}
                                />
                              ))
                            }
                          </Panel>
                         
                        </Collapse> */}
                  {/* <Col span={10} style={{ textAlign: "center" }}>开始时间 : </Col> */}
                  <Col span={24} style={{ textAlign: "center" }}><DatePicker size="small" placeholder="请选择开始时间" style={{ width: "253px" }} /></Col>

                  {/* <Col span={10} style={{ textAlign: "center", marginTop: "20px" }}>结束时间 : </Col> */}
                  <Col span={24} style={{ textAlign: "center", marginTop: "20px" }}><DatePicker size="small" placeholder="请选择结束时间" style={{ width: "253px" }} /></Col>
                  <Col style={{ textAlign: "center", backgroundColor: "#E1E9F5", marginTop: "10px", height: 6 }} span={24}></Col>
                  <Col span={24}> <br /></Col>
                  <div className={styles.blueBlock} style={{ paddingTop: '10px' }}><i style={{ height: 14, width: 5, backgroundColor: "#3C8FFF", marginRight: 20 }}></i><span style={{ textAlign: "left", fontWeight: 'normal', margin: "0 10px", borderBottom: "1px solid #ccc", paddingBottom: 10 }}> 视频列表</span></div>
                  <Col span={24} style={{height:"40vh",overflow:"auto"}}>

                    <Tree
                      // checkable
                      defaultExpandedKeys={["0-0"]}
                      // defaultExpandAll={true}
                      // onCheck={this.onCheck}
                      // autoExpandParent={true}
                      onSelect={this.onDragEnter}
                    >
                      {this.renderTreeNodes(treeData)}
                    </Tree>
                  </Col>
                  <br />
                  <div style={{position:"absolute",bottom:"1vh",width:"100%"}}>
                  <div className={styles.blueBlock} style={{ paddingTop: '10px' }}><i style={{ height: 14, width: 5, backgroundColor: "#3C8FFF", marginRight: 20 }}></i><span style={{ textAlign: "left", fontWeight: 'normal', margin: "0 10px", borderBottom: "1px solid #ccc", paddingBottom: 10 }}> 已选取</span></div>
                  <br />
                  <Col span={24} style={{ height:"1.5vh",lineHeight:0,marginLeft:"9%" }}>{this.state.treeValue}</Col>
                  <Col span={12} style={{ textAlign: "center" }}><Button type="primary" size="small" style={{ width: "70px", marginTop: "20px" }} onClick={this.onOPen}>播放</Button></Col>

                  <Col span={12} style={{ textAlign: "center" }}><Button size="small" style={{ width: "70px", marginTop: "20px", color: "#fff", backgroundColor: "#FF9C3F" }} onClick={this.pause}>关闭</Button></Col>
                  </div>
                
                </div>
              </Row>
            </div>
          </Col>
        </Row>
      </div>
    )
  }
}

function mapStateToProps(state) {
  return {
  };
}
export default connect(mapStateToProps)(DragDropContext(HTML5Backend)(VideoHistory));